import Vue from "vue";
import {
	loading,
	toast,
	getCache,
	setCache
} from './utils'

export function upload(obj) {
	console.log('走到了这里')
	let that = this
	obj.fail = obj.fail || function(res) {
		console.log(res);
	};
	let loading = obj.loading || true
	let url = 'http://betogethe.sd.wmkjpro.cn/betogether/api.Upload/file';
	let formData = obj.data || {};
	let name = obj.name || 'file';
	let token = '';
	console.log(obj,'url',url)
	if (getCache('token')) {
		// console.log(util.getCache('token'),'sddddddddd');
		token = getCache('token')
	}
	//album 相册选图  // camera相机选图
	let sourceType = obj.sourceType || ['album', 'camera'];
	obj.count = obj.count || 1;
	uni.chooseImage({
		count: obj.count, // 默认9
		sizeType: 'compressed',
		sourceType: sourceType, // 可以指定来源是相册还是相机
		success: (res) => {
			console.log(res);
			let tempFilePaths = res.tempFilePaths
			if (loading) {
				// 	loading('上传中...');
				uni.showLoading({
					title: '上传中...',
					icon: 'loading',
					mask: true
				})
			}
			let ResulData = [];
			let num = 0;
			tempFilePaths.forEach(function(value) {
				uni.uploadFile({
					header: {
						'token': token,
					},
					url: url, //仅为示例，非真实的接口地址
					filePath: value,
					name: name,
					formData: formData,
					success: function(res) {
						if (loading) {
							uni.hideLoading();
						}
						let data = JSON.parse(res.data);
						console.log(data, 'datatat')

						if (data.code === -1) {
							// uni.clearStorageSync();
							// util.openLogin();
							obj.fail(data.msg);
							// uni.reLaunch({
							// 	url: '/pages/login/login'
							// })
							return;
						}
						if (data.code == 1) {
							num = parseInt(num) + parseInt(1);
							ResulData.push(data.data);
							if (num == tempFilePaths.length) {
								if (obj.count == 1) {
									obj.success(data.data);
								} else {
									obj.success(ResulData);
								}
							}
						} else {
							toast(data.msg);
							obj.fail(data);
							return;
						}
					},
					fail: (res) => {
						if (loading) {
							uni.hideLoading();
						}
						obj.fail(res);
						return;
					}
				});
			})
		},
		fail: err => {
			obj.fail('网络错误');
		}
	})
}